import React from 'react';

// 引入路由相应的API
import { BrowserRouter, useRoutes } from 'react-router-dom';

// 获取所有的页面路由
import routes from "~react-pages";
const App = () => 
{
    const Routers = () =>
    {
        // 定义一个跳转页面的属性
        let navigate = useNavigate();

        React.navigate = navigate;

        // 获取当前路径
        const { pathname } = useLocation();

    useEffect(() => {        
        const check = async () =>
        {
            let business = React.Cookies.load('business') ?? {};

            if(Object.getOwnPropertyNames(business).length === 0)
            {
                React.navigate('/business/login',{ replace:true });
                React.toast('请先登录');
                return false;
            }

            let id = business.id ?? 0;
            let mobile = business.mobile ?? '';

            let result = await React.Http.post('/business/check',{id,mobile});

            if(result.code === 1)
            {
                React.Cookies.save('business', result.data, {path: '/'});

                return true;
            }else{
                React.navigate('/business/login',{ replace: true });
                React.toast(result.msg, null, 'fail');
                React.Cookies.remove('business');
    
                return false;
            }
            
        }

        // 当前路由是否在规则里
        if(!React.RouterRules.includes(pathname)) check();

    },[pathname,navigate]);

    // 返回自动生成的路由列表
    return (
        <React.Suspense fallback={<React.UI.AutoCenter><React.UI.DotLoading color='primary' /></React.UI.AutoCenter>}>
            {useRoutes(routes)}
        </React.Suspense>
    );
}

return (
    <BrowserRouter>
        <Routers />
    </BrowserRouter>
)
}

export default App;
